package com.dzjcloud.dzj.common.fegin;

import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <h3>dzj-cloud</h3>
 * <p>fegin拦截器</p>
 *
 * @author : DongZeJian
 * @date : 2021-05-31 11:54
 **/
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 传递令牌
        // 1.获取request请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes !=null){
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            // 2.获取所有的请求头
            String authorization = request.getHeader("Authorization");
            // 3.判断请求头不为空的话就组装token传输
            if (StrUtil.isNotBlank(authorization)){
                requestTemplate.header("Authorization",authorization);
            }
        }
    }
}

